<template>
    <view class="pay-page">
        <!-- 缴费信息 -->
        <view class="pay-info">
            <view class="pay-title">正在缴费 [个人会员费]</view>
            <view class="pay-org">执行与收款机构：枣庄市红十字会</view>
        </view>

        <!-- 青少年免费提示 -->
        <view v-if="isTeenager" class="teenager-notice">
            <view class="notice-icon">🎉</view>
            <view class="notice-content">
                <view class="notice-title">青少年会员免费</view>
                <view class="notice-desc">您符合青少年会员条件，本次缴费免费</view>
            </view>
        </view>

        <!-- 金额选择 -->
        <view class="amount-section" v-if="!isTeenager">
            <view class="section-title">金额</view>
            
            <!-- 加载状态 -->
            <view v-if="isLoading" class="loading-state">
                <view class="loading-text">加载中...</view>
            </view>
            
            <!-- 金额选项 -->
            <view v-else-if="amountOptions.length > 0" class="amount-grid">
                <view 
                    v-for="(amount, index) in amountOptions" 
                    :key="index"
                    class="amount-item"
                    :class="{ 'selected': selectedFeeId === amount.id }"
                    @click="selectAmount(amount.id, amount.amount)"
                >
                    <view class="amount-content">
                        <text class="amount-text">¥{{ amount.amount }}</text>
                        <!-- <text v-if="amount.title" class="amount-title">{{ amount.title }}</text> -->
                    </view>
                    <image v-if="selectedFeeId === amount.id" src="../../static/checked.png" class="check-icon"></image>
                </view>
            </view>
            
            <!-- 无数据状态 -->
            <view v-else class="empty-state">
                <view class="empty-text">暂无金额选项</view>
            </view>

            <!-- 总数显示 -->
            <view v-if="selectedFeeId" class="total-section">
                <view class="section-title">总数</view>
                <view class="total-amount">¥{{ totalAmount }}</view>
            </view>
    
            <!-- 支付方式 -->
            <view class="payment-section">
                <view class="section-title">支付方式</view>
                <view class="payment-method">
                    <view class="method-item">
                        <view class="method-left">
                            <image src="../../static/wechat.png" class="method-icon"></image>
                            <text class="method-text">微信支付</text>
                        </view>
                        <view class="method-right">
                            <view class="radio-btn selected"></view>
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <!-- 青少年免费缴费信息 -->
        <view v-if="isTeenager" class="teenager-payment">
            <view class="section-title">缴费信息</view>
            <view class="teenager-info">
                <view class="info-item">
                    <text class="info-label">缴费金额：</text>
                    <text class="info-value free">免费</text>
                </view>
                <view class="info-item">
                    <text class="info-label">支付方式：</text>
                    <text class="info-value">免费注册</text>
                </view>
            </view>
        </view>

        <!-- 底部确认按钮 -->
        <view class="footer-btn">
            <view 
                class="primary-btn" 
                :class="{ 'loading': isPaying, 'disabled': isLoading || (!isTeenager && !selectedFeeId) }"
                @click="confirmPayment"
            >
                {{ isPaying ? '处理中...' : (isLoading ? '加载中...' : (isTeenager ? '确认免费注册' : '确定')) }}
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import PaymentUtil from '../../utils/payment.js'
import { getFeeList } from '../../utils/api.js'

// 金额选项
const amountOptions = ref([])

// 选中的费用ID
const selectedFeeId = ref('')

// 选中的金额
const selectedAmount = ref(0)

// 支付状态
const isPaying = ref(false)

// 加载状态
const isLoading = ref(true)

// 是否为青少年
const isTeenager = ref(false)

// 计算总数（这里可以根据业务逻辑调整）
const totalAmount = computed(() => {
    return selectedAmount.value
})

// 获取用户信息并判断是否为青少年
const checkTeenagerStatus = () => {
    try {
        const userInfo = uni.getStorageSync('user_info')
        if (userInfo) {
            // 如果用户信息是字符串，转换为对象
            const userData = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
            
            // 判断是否为青少年 (isTeenager: 1表示是，0表示否)
            isTeenager.value = userData.isTeenager === 1
            
            console.log('用户信息:', userData)
            console.log('是否为青少年:', isTeenager.value)
        }
    } catch (error) {
        console.error('获取用户信息失败:', error)
        isTeenager.value = false
    }
}

// 加载费用列表
const loadFeeList = async () => {
    try {
        isLoading.value = true
        const result = await PaymentUtil.getFeeList()
        
        if (result.code == 0) {
            amountOptions.value = result.data || []
            // 默认选择第一个金额选项
            if (amountOptions.value.length > 0) {
                selectedFeeId.value = amountOptions.value[0].id
                selectedAmount.value = amountOptions.value[0].amount
            }
        } else {
            throw new Error(result.message || '获取费用列表失败')
        }
    } catch (error) {
        console.error('加载费用列表失败:', error)
        uni.showToast({
            title: error.message || '加载费用列表失败',
            icon: 'none'
        })
        // 如果接口失败，使用默认金额选项
        amountOptions.value = [
            { id: '1', amount: 10, title: '10元' },
            { id: '2', amount: 20, title: '20元' },
            { id: '3', amount: 50, title: '50元' },
            { id: '4', amount: 100, title: '100元' },
            { id: '5', amount: 200, title: '200元' },
            { id: '6', amount: 500, title: '500元' }
        ]
        selectedFeeId.value = '2'
        selectedAmount.value = 20
    } finally {
        isLoading.value = false
    }
}

// 选择金额
const selectAmount = (feeId, amount) => {
    selectedFeeId.value = feeId
    selectedAmount.value = amount
}

// 确认支付
const confirmPayment = async () => {
    if (isPaying.value) return
    
    // 如果是青少年，直接处理免费注册
    if (isTeenager.value) {
        await handleTeenagerRegistration()
        return
    }
    
    // 验证金额
    if (!PaymentUtil.validateAmount(selectedAmount.value)) {
        uni.showToast({
            title: '请选择有效的支付金额',
            icon: 'none'
        })
        return
    }
    
    // 验证费用ID
    if (!selectedFeeId.value) {
        uni.showToast({
            title: '请选择支付金额',
            icon: 'none'
        })
        return
    }
    
    isPaying.value = true
    
    try {
        // 获取用户信息
        const userInfo = uni.getStorageSync('user_info') ? uni.getStorageSync('user_info') : {}
        const userId = userInfo?.id || ''
		console.log(userInfo)
        
        if (!userId) {
            throw new Error('用户信息获取失败，请重新登录')
        }
        
        // 执行支付流程
        const result = await PaymentUtil.processPayment(
            selectedFeeId.value,
            selectedAmount.value, 
            userId, 
            'membership'
        )
        
        // 支付成功
        uni.showToast({
            title: '支付成功',
            icon: 'success'
        })
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
            uni.navigateTo({
                url: `/pages/my/payResult?status=success&amount=${selectedAmount.value}`
            })
        }, 1500)
        
    } catch (error) {
        console.error('支付流程失败:', error)
        
        // 处理错误信息
        const errorMessage = PaymentUtil.handlePaymentError(error)
        
        uni.showToast({
            title: errorMessage,
            icon: 'none'
        })
        
        // 如果是支付失败（非取消），跳转到失败页面
        if (error.errMsg && !error.errMsg.includes('cancel')) {
            setTimeout(() => {
                uni.navigateTo({
                    url: `/pages/my/payResult?status=fail&amount=${selectedAmount.value}`
                })
            }, 1500)
        }
    } finally {
        isPaying.value = false
    }
}

// 处理青少年免费注册
const handleTeenagerRegistration = async () => {
    isPaying.value = true
    
    try {
        // 获取用户信息
        const userInfo = uni.getStorageSync('user_info')
        const userId = userInfo?.id || ''
        
        if (!userId) {
            throw new Error('用户信息获取失败，请重新登录')
        }
        
        // 青少年直接调用缴费接口，feeId传-1，金额为0
        const result = await PaymentUtil.processPayment(
            -1, // feeId传-1
            0,  // 金额为0
            userId, 
            'membership'
        )
        
        // 注册成功
        uni.showToast({
            title: '免费注册成功',
            icon: 'success'
        })
        
        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
            uni.navigateTo({
                url: `/pages/my/payResult?status=success&amount=0&teenager=true`
            })
        }, 1500)
        
    } catch (error) {
        console.error('青少年注册失败:', error)
        
        uni.showToast({
            title: error.message || '注册失败，请重试',
            icon: 'none'
        })
    } finally {
        isPaying.value = false
    }
}

// 页面加载时获取费用列表
onMounted(() => {
    checkTeenagerStatus()
    if (!isTeenager.value) {
        loadFeeList()
    } else {
        isLoading.value = false
    }
})
</script>

<style lang="scss" scoped>
.pay-page {
    min-height: 100vh;
    background: #f5f5f5;
    padding: 24rpx;
    padding-bottom: 200rpx;
}

.pay-info {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
    margin-bottom: 24rpx;
    border: 2rpx solid #E7E8EB;
    font-size: 28rpx;
    color: rgba(0, 0, 0, 0.80);
    line-height: 40rpx;

    .pay-title {
        margin-bottom: 24rpx;
    }
}

.teenager-notice {
    background: linear-gradient(135deg, #FFE9DA 0%, #FFF2F0 100%);
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
    margin-bottom: 24rpx;
    border: 2rpx solid #FFD6C7;
    display: flex;
    align-items: center;

    .notice-icon {
        font-size: 48rpx;
        margin-right: 24rpx;
    }

    .notice-content {
        flex: 1;

        .notice-title {
            font-size: 32rpx;
            font-weight: 600;
            color: #F9623E;
            margin-bottom: 8rpx;
        }

        .notice-desc {
            font-size: 26rpx;
            color: #666;
            line-height: 36rpx;
        }
    }
}

.amount-section {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
    border: 2rpx solid #E7E8EB;

    .section-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 24rpx;
    }

    .loading-state {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 150rpx; /* Adjust height as needed */
    }

    .loading-text {
        font-size: 32rpx;
        color: #666;
    }

    .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 150rpx; /* Adjust height as needed */
    }

    .empty-text {
        font-size: 32rpx;
        color: #999;
    }

    .amount-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 26rpx;

        .amount-item {
            position: relative;
            height: 88rpx;
            background: #fff;
            border: 2rpx solid #E7E8EB;
            border-radius: 16rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            cursor: pointer;
            font-size: 32rpx;

            &.selected {
                background: #FFF2F0;
                border-color: #EC4637;
                color: #EC4637;

                .amount-text {
                    color: #EC4637;
                }

                .check-icon {
                    position: absolute;
                    bottom: 0rpx;
                    right: 0rpx;
                    width: 48rpx;
                    height: 48rpx;
                }
            }

            .amount-content {
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                height: 100%;
            }

            .amount-text {
                font-size: 32rpx;
                font-weight: 600;
                color: #333;
                transition: color 0.3s ease;
            }

            .amount-title {
                font-size: 24rpx;
                color: #999;
                margin-top: 4rpx;
            }
        }
    }
}

.teenager-payment {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
    border: 2rpx solid #E7E8EB;

    .section-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 24rpx;
    }

    .teenager-info {
        .info-item {
            display: flex;
            align-items: center;
            padding: 16rpx 0;
            border-bottom: 2rpx solid #f0f0f0;

            &:last-child {
                border-bottom: none;
            }

            .info-label {
                font-size: 28rpx;
                color: #666;
                width: 160rpx;
                flex-shrink: 0;
            }

            .info-value {
                font-size: 28rpx;
                color: #333;
                font-weight: 500;

                &.free {
                    color: #0EBD70;
                    font-weight: 600;
                }
            }
        }
    }
}

.pay-info {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx 24rpx;
}
    
.total-section {

    .section-title {
        margin-top: 48rpx;
    }

    .total-amount {
        font-size: 36rpx;
        font-weight: 600;
        color: #F9623E;
        padding-bottom: 26rpx; 
        border-bottom: 2rpx solid #e7e7e7;
    }
}

.payment-section {

    .section-title {
        margin-top: 48rpx;
    }

    .payment-method {
        .method-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 24rpx 0;

            .method-left {
                display: flex;
                align-items: center;
                gap: 16rpx;

                .method-icon {
                    width: 48rpx;
                    height: 48rpx;
                }

                .method-text {
                    font-size: 28rpx;
                    color: #333;
                }
            }

            .method-right {
                .radio-btn {
                    width: 32rpx;
                    height: 32rpx;
                    border: 2rpx solid #ddd;
                    border-radius: 50%;
                    position: relative;

                    &.selected {
                        border-color: #F9623E;
                        background: #F9623E;

                        &::after {
                            content: '';
                            position: absolute;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%);
                            width: 12rpx;
                            height: 12rpx;
                            background: #fff;
                            border-radius: 50%;
                        }
                    }
                }
            }
        }
    }
}

.footer-btn {
    position: fixed;
    bottom: 0;
    left: 0;
    width: calc(100% - 48rpx);
    height: 100rpx;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24rpx 24rpx 28rpx 24rpx;
    z-index: 100;
    
    .primary-btn {
        width: 100%;
        height: 88rpx;
        background: #F9623E;
        color: #fff;
        border-radius: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 32rpx;
        font-weight: 600;
        transition: all 0.3s ease;
        
        &.loading {
            background: #ccc;
            pointer-events: none;
        }

        &.disabled {
            background: #ccc;
            color: #999;
            pointer-events: none;
        }
        
        &:active {
            transform: scale(0.98);
        }
    }
}
</style>
